package com.mind.core.net.websocket.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;

import java.nio.ByteOrder;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mind.core.net.handler.HandlerManager;
import com.mind.core.net.msg.Message;

public class WebsocketBinaryDecoder extends
		MessageToMessageDecoder<WebSocketFrame> {
	private final static Logger logger = LoggerFactory.getLogger("decoder");
	@Override
	protected void decode(ChannelHandlerContext ctx, WebSocketFrame msg,
			List<Object> out) throws Exception {
		if(!(msg instanceof BinaryWebSocketFrame)){
			return ;
		}
		ByteBuf in=msg.content();
		int leftNum = in.readableBytes();
		if (leftNum < Message.MIN_MESSAGE_LENGTH) {
			return;
		}
		int len = in.readShort();
		if (in.readableBytes() < (len - Message.HEADER_LEN_BYTES)) {
			return;
		}
		short type = in.readShort();
		ByteBuf buf = ctx.alloc().buffer(len);
		buf.writeShort(len);
		buf.writeShort(type);
		buf.writeBytes(in, len - Message.MIN_MESSAGE_LENGTH);
		Message message = HandlerManager.createMessage(type);
		message.setBuffer(buf);
		if (!message.read()) {
			throw new Exception("decoder  wrong!message code=" + type);
		}
		out.add(message);
	}
}
